package com.dxysun.springboot.reslover;

import com.alibaba.fastjson.JSON;
import com.dxysun.springboot.dto.User;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.MethodParameter;
import org.springframework.util.Base64Utils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletRequest;

@Configuration
public class UserParamResolver implements HandlerMethodArgumentResolver
{
    private static final Log logger = LogFactory.getLog(UserParamResolver.class);

    @Override
    public boolean supportsParameter(MethodParameter methodParameter)
    {
        return User.class.isAssignableFrom(methodParameter.getParameterType());
    }

    @Override
    public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest, WebDataBinderFactory webDataBinderFactory) throws Exception
    {
        HttpServletRequest request = nativeWebRequest.getNativeRequest(HttpServletRequest.class);
        String msg = request.getParameter("msg");
        if(StringUtils.isEmpty(msg))
        {
            return null;
        }
        if("error".equals(msg))
        {
            throw new RuntimeException("resolveArgument 异常");
        }
//        Class<?> clazz = methodParameter.getParameterType();
        Class<? extends User> parameterType = (Class<? extends User>) methodParameter
                .getParameterType();
        User user = JSON.parseObject(Base64Utils.decodeFromString(msg), parameterType);

        logger.info("in Resolver:" + JSON.toJSONString(user));
        logger.info("in Resolver request:" + request);

        return user;
    }
}
